// Media module
// Add media reinit by regret

#include "burner.h"

static int baseFps;

// Media init / exit
int mediaInit()
{
	if (scrnInit()) {					// Init the Scrn Window
		return 1;
	}

	if (!inputOkay) {
		inputInterface.init();			// Init Input
	}

	baseFps = BurnGetRefreshRate();
	appVirtualFps = BurnGetRefreshRate();

	if (!audOkay) {
		audioInterface.init();			// Init Sound (not critical if it fails)

		if (!audOkay) {
			// Make sure the error will be visible
			splashDestroy(1);
			FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_UI_MODULE), audioInterface.getName());
			FBAPopupDisplay(PUF_TYPE_ERROR);
		}
	}

	nBurnSoundRate = 0;					// Assume no sound
	pBurnSoundOut = NULL;
	if (audOkay) {
		nBurnSoundRate = audSampleRate;
		nBurnSoundLen = audSegLen;
	}

	if (!vidOkay) {
		if (!vidFullscreen) {
			scrnSize();
		}

		// Reinit the video plugin
		videoInterface.init();

		if (!vidOkay && vidFullscreen) {
			vidFullscreen = 0;
			mediaExit();
			return (mediaInit());
		}

		if (!vidOkay && (driverOkay || vidUsePlaceholder)) {
			// Make sure the error will be visible
			splashDestroy(1);
			FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_UI_MODULE), videoInterface.getName());
			FBAPopupDisplay(PUF_TYPE_ERROR);
		}

		if (vidOkay && !driverOkay) {
			videoInterface.redraw();
		}
	}

	runInit();

	gameInpCheckLeftAlt();
	gameInpCheckMouse();				// Hide the cursor

	return 0;
}

int mediaExit()
{
	nBurnSoundRate = 0;					// Blank sound
	pBurnSoundOut = NULL;

	audioInterface.exit();				// Exit audio

	videoInterface.exit();

	inputInterface.exit();

	dialogManager.remove(IDD_INPS);
	dialogManager.remove(IDD_INPD);

	return 0;
}

int mediaReInit()
{
	runExit();
	mediaExit();
	return mediaInit();
}

// reinit audio, added by regret
int mediaReInitAudio()
{
	if (audioInterface.audPlaying) {
		audioInterface.stop();
	}

	nBurnSoundRate = 0;					// Blank sound
	pBurnSoundOut = NULL;

	if (audioInterface.exit()) {
		return 1;
	}

	if (audioInterface.init()) {
		FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_UI_MODULE), audioInterface.getName());
		FBAPopupDisplay(PUF_TYPE_ERROR);
		return 1;
	}

	nBurnSoundRate = audSampleRate;
	nBurnSoundLen = audSegLen;

	runInit();

	return 0;
}

// change FPS
int mediaChangeFps(int scale)
{
	appVirtualFps = baseFps * scale / 100;

	if (!audOkay) {
		return 1;
	}

	if (audioInterface.audPlaying) {
		audioInterface.stop();
	}

	if (audioInterface.setfps()) {
		return 1;
	}

	nBurnSoundRate = audSampleRate;
	nBurnSoundLen = audSegLen;
	audioInterface.play();

	return 0;
}
